<template lang="">
    <div>
        <div id="main" ref="main"></div>
    </div>
</template>
<script>
    import * as echarts from 'echarts/core';

    export default {
        name: 'BarCharts',
        props: ['item'],
        data() {
            return {
                myChart: '',
                option: {
                    yAxis: {
                        type: 'category',
                        data: []
                    },
                    xAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            data: [],
                            type: 'bar',
                            showBackground: true,
                            backgroundStyle: {
                                color: 'rgba(180, 180, 180, 0.2)'
                            }
                        }
                    ]
                }
            }
        },
        watch: {
            item(newValue) {
                this.option.series[0].data = []
                this.option.yAxis.data = []
                for (let i = 0; i < newValue.option.length; i++) {
                    this.option.series[0].data.push(newValue.option[i].value)
                    this.option.yAxis.data.push(newValue.option[i].name)
                }
                this.$nextTick(() => {
                    this.myChart.setOption(this.option, true);
                })
            }
        },
        methods: {
            resize() {
                this.myChart.resize();
            }
        },
        mounted() {
            console.log('this.item', this.item);
            var chartDom = this.$refs.main;
            this.myChart = echarts.init(chartDom);
            for (let i = 0; i < this.item.option.length; i++) {
                this.option.series[0].data.push(this.item.option[i].value)
                this.option.yAxis.data.push(this.item.option[i].name)
            }
            console.log('柱状图', this.item);
            this.myChart.setOption(this.option, true);
            window.addEventListener("resize", this.resize);
        },
        beforeDestroy() {
            window.removeEventListener('resize',this.resize)
        },
    }
</script>
<style scoped>
    #main {
        height: 300px;
        margin: 0 auto;
    }
</style>